package com.zm.devmag.base.init;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.util.IOUtils;
import com.zm.devmag.back.vo.Admin;
import com.zm.devmag.util.CalendarUtil;

@Component
public class Initialize {
	
	private Logger logger = LoggerFactory.getLogger(Initialize.class);
	
	private String filePath = null;
	
	private Properties prop = null;
	/**
	 * 初始化数据容量
	 */
	public ConcurrentMap<String,Object> model = new ConcurrentHashMap<String,Object>();
	/**
	 * 初始化数据
	 */
	@PostConstruct
	public void init(){
		try{
			prop = new Properties();
			filePath = this.getClass().getClassLoader().getResource("config.properties").toURI().getPath();
			prop.load(this.getClass().getClassLoader().getResourceAsStream("config.properties"));
			initAdmin(prop);
		}catch(Exception e){
			logger.error("[初始化数据读取失败]",e);
		} 		
	}
	/**
	 * 初始化超级管理员
	 */
	public void initAdmin(Properties prop){
		String name = (String) prop.get("name");
		String password  = (String) prop.get("password");
		String ratestr = (String) prop.get("score_rate");
		Double score_rate = Double.parseDouble(ratestr);
		Admin admin = new Admin(name,password,score_rate);
		model.put("admin", admin);
	}
	/**
	 * 
	 * 修改管理员
	 * @param password:密码
	 * @param rate:兑换积分比率
	 */
	public void update(String password,Double rate){
		FileOutputStream fos = null;
		try{
			prop.setProperty("password", password == null ?"123":password);
			fos = new FileOutputStream(filePath);
			prop.setProperty("score_rate", String.valueOf(rate));
			prop.store(fos, CalendarUtil.getCurr("yyyy-MM-dd HH:mm:ss") +" edit admin");
			IOUtils.close(fos);
			initAdmin(prop);
		}catch(IOException e){
			logger.error("[修改Admin错误]",e);
		}finally{
			if(fos != null){
				IOUtils.close(fos);
			}
			
		}
	}
	
	
}
